package services

import (
	"fmt"
	"time"

	"github.com/dgrijalva/jwt-go"
	"gitverse.ru/tokuara/impleo/restapi/configs"
)

func GenerateJWT() (string, error) {
	secretkey := configs.JWTSecretKey()

	userId := "1234567890"

	expirationTime := time.Now().Add(12 * time.Hour).Unix()

	token := jwt.NewWithClaims(
		jwt.SigningMethodHS256,
		jwt.StandardClaims{
			ExpiresAt: expirationTime,
			Subject:   userId,
		},
	)

	return token.SignedString([]byte(secretkey.Key))
}

func GetRefreshJWT() (string, error) {
	//secretkey := configs.JWTSecretKey()

	return "", nil
}

func GetIdFromJWT(requestJWT string) (string, error) {
	secretkey := configs.JWTSecretKey()

	token, err := jwt.Parse(requestJWT, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method %s", token.Header["alg"])
		}
		return []byte(secretkey.Key), nil
	})

	if err != nil {
		return "", err
	}

	claims, ok := token.Claims.(jwt.MapClaims)

	if !ok && !token.Valid {
		return "", fmt.Errorf("invalid token")
	}

	return claims["sub"].(string), nil
}
